from Lib.Core.Scene import Scene


class LoadingScene(Scene):
    def __init__(self):
        super().__init__("LoadingScene")
        from constants import game
        game.scene = None
        self.min_wait_time = 3000
        self.time = 0
        from constants import game
        game.list_update.append(self.WaitLoading)
        self.is_loaded = False
        self.is_waited = False
        self.scene_name = ""

        from Lib.Core.UISprite import UISprite
        from constants import window_size
        from constants import config
        import pygame
        background = pygame.transform.scale(
                pygame.image.load(f"{config.get('base', 'resource_path')}images/loading_background.jpg"), window_size)
        game.ui_group.add(UISprite(background))

        self.font = pygame.font.Font(config.get('base', 'font_path'), 16)
        self.surface = self.font.render(f"正在 初始化加载...", True, [255, 0, 0])
        self.sp = UISprite(self.surface)
        from Lib.Core.UIResponse import UIResponse
        from Lib.Core.Game import UILayer
        self.re = UIResponse([500, 500, 1000, 50], UILayer.MID.value)
        self.re.add(self.sp)
        self.re.CorrectPosition()
        game.ui_group.add(self.re)

        from Lib.UtilsGame import CutScreenBlack
        CutScreenBlack("in")

    def Load(self, scene_name):
        self.scene_name = scene_name

        def SceneLoaded():
            self.is_loaded = True
            text = f"正在构建新的世界..."
            self.sp.image = self.font.render(text, True, [255, 0, 0])

        import locals
        from Lib.Core.LocalResource import LocalResource
        locals.resource = LocalResource(self.Loading, SceneLoaded)
        locals.resource.Load(scene_name)

    def Loading(self, current, count, resource, path, key):
        text = f"正在加载：{path}"
        self.sp.image = self.font.render(text, True, [255, 0, 0])

    def WaitLoading(self, dt):
        if not self.is_waited:
            self.time += dt
            if self.time >= self.min_wait_time:
                self.is_waited = True
        if self.is_loaded and self.is_waited:
            self.Destroy()
            module_path = f"Scenes.{str(self.scene_name)}.{str(self.scene_name)}"
            from Lib.Utils import SyncGeneratorScene
            from constants import game
            from Lib.UtilsGame import CutScreenBlack

            def InScene():
                game.scene = SyncGeneratorScene(module_path, self.scene_name)

            CutScreenBlack("out", _callable=InScene)

    def Destroy(self):
        from constants import game
        game.list_update.remove(self.WaitLoading)
        from Lib import UtilsGame
        UtilsGame.ClearUI()
